﻿(function (angular) {

    angular.module("app.dictionary-grid")
        .factory("wordData", wordData)

    wordData.$inject = ["$http", "$q", "$log"];
    function wordData($http, $q, $log) {
        var service = {
            getWords: getWords,
            addWord: addWord,
            deleteWord: deleteWord
        };

        return service;

        function onQueryFailed(response) {
            $log.error("Failed " + response);
            alert("Error");
        }

        function getWords() {
            var defer = $q.defer();

            function succeedQuery(response) {
                defer.resolve(response.data);
            }

            $http({
                method: "GET",
                url: "/api/Dictionary/GetWords"
            }).then(succeedQuery, onQueryFailed)

            return defer.promise;
        }

        function addWord(word) {
            var defer = $q.defer();

            function succeedQuery(response) {
                defer.resolve();
            }

            $http({
                method: "POST",
                data: word,
                url: "/api/Dictionary/AddWord"
            }).then(succeedQuery, onQueryFailed)

            return defer.promise;
        }

        function deleteWord(wordGuid) {
            var defer = $q.defer();

            function succeedQuery(response) {
                defer.resolve();
            }

            $http({
                method: "DELETE",
                url: "/api/Dictionary/DeleteWord?wordGuid=" + wordGuid
            }).then(succeedQuery, onQueryFailed)

            return defer.promise;
        }
    }

})(angular)